import getLocationAuth from '@/utils/getLocationAuth.js'
export default {
  data() {
    return {
      pageLoading: false,
      successAdd: false,//定位成功
      res: {},
      isBlock: true, //搜索框显示
      isGetAdd: false, //重新定位loading
      lat: 0, //经度
      lon: 0, //维度
      lodding: false, //选择区县loading
      isCity: true, //
      cityId: 0, //城市id
      gotList: [], //热门列表
      downShow: false, //下拉显示
      isOpen: false, //开关
      city: '', //城市名
      province: '', //省份
      district: '', //区
      search: '', //搜索的值
      scrollTop: 0, //顶部距离
      cityList: '', //城市列表
      hasList: false,
      isListShow: true, //
      indexList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'W', 'X', 'Y', 'Z', '#'
      ],
      newArr: [],
      arr: [], //搜索城市值
      a: [], //过滤的值
      isShow: false, //搜索列表显示
      pinyin: '', //拼音
      findDistrict: [], //区县列表
      allList: [], //全部地址
      postalCode: 0,
      swiperheight: 0,
      wxgetlat:false,//判断微信是否同意授权经纬度
    }
  },
  watch: {

  },
  onLoad() {
    uni.getSystemInfo({
      success: res => {
        let height = res.windowHeight - uni.upx2px(100) //获取系统信息，可使用窗口的高度
        this.swiperheight = height
      }
    })
  },
  created() {
    this.location()
    this.cityId = this.$store.state.postalCode //邮编
    this.getCityList()
    this.getHotCity()
  },
  onShow(){
    this.regionaldistrict()
    //微信同意授权经纬度
    if(this.wxgetlat){
      this.location()
    }
  },
  mounted() {
    //#ifdef H5
    //核心开始------------------------------------
    let oldTop = 0 //旧数据，初始为0
    // 将自定义方法绑定到窗口滚动条事件
    window.onscroll = () => {
      let top = document.scrollingElement.scrollTop //触发滚动条，记录数值
      //旧数据大于当前位置，表示滚动条top向上滚动
      if (oldTop >= top) {
        this.isBlock = true
      } else {
        //相反...
        this.isBlock = false
      }
      oldTop = top //更新旧的位置
    }
    //#endif
  },
  computed: {
    vuexCity(){
      return this.$store.state.city
    },
    vuexDistrict(){
      return this.$store.state.district
    }
  },
  methods: {
    async chooseCity(){
      let res = this.res
      await this.getCityList2(res.address.city, res.address.district)
      let addArr = {
        city: res.address.city,
        province: res.address.province,
        district: res.address.district,
        postalCode: this.postalCode, //id
        lon: res.longitude, //经度
        lat: res.latitude
      }
      this.$store.dispatch('changeAddress', addArr)
      uni.setStorageSync('addressList', addArr)
      this.cityId = this.postalCode
      uni.navigateBack({
			  delta: 1,
      })
    },
    touchmove(e) {
      //#ifdef APP-PLUS
      let top = e.changedTouches[0].clientY
      if (this.isSearch || this.listShow) return false
      if (top >= this.clientY) {
        this.isBlock = true
      } else {
        this.isBlock = false
      }
      //#endif
    },
    touchstart(e) {
      //#ifdef APP-PLUS
      this.clientY = e.changedTouches[0].clientY
      //#endif
    },
    //定位全部区县
    async regionalAll() {
      this.lodding = true
      try {
        const {
          data
        } = await this.$api.jsonData.regionalAll()

        let that = this
        data.Item.childlist.map(item1 => {
          item1.childlist.map(item2 => {
            if (item2.name === res.address.city) {
              this.findDistrict = item2.childlist
            }
          })
        })
        this.lodding = false
      } catch (e) {
        this.lodding = false
      }
    },
    //获取市区
    async getCityList2(address, district) {
      try {
        const {
          data
        } = await this.$api.jsonData.regionaldistrict()
        let add = data.Item.find(item => item.name === district)
        this.postalCode = Number(add.id)
      } catch (e) {

      }
    },
    //定位
    location() {
      //#ifdef APP-PLUS
      uni.showLoading({
        title: '获取中'
      })
      this.isGetAdd = true
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        success: res => {
          this.successAdd = true
          this.res = res
          // await this.getCityList2(res.address.city, res.address.district)
          // this.city = res.address.city
          // this.province = res.address.province
          // this.district = res.address.district
          // this.cityId = this.postalCode
          uni.hideLoading()
          this.isGetAdd = false
          /* this.$store.dispatch('changeAddress', {
            city: res.address.city,
            province: res.address.province,
            district: res.address.district,
            postalCode: this.postalCode, //id
            lon: res.longitude, //经度
            lat: res.latitude
          })
          uni.setStorageSync('addressList', {
            city: res.address.city,
            province: res.address.province,
            district: res.address.district,
            postalCode: this.postalCode, //id
            lon: res.longitude, //经度
            lat: res.latitude
          }) */
          // this.regionalAll()
        },
        fail: () => {
          this.successAdd = false
          this.isGetAdd = false
          uni.hideLoading()
          getLocationAuth() // 获取系统定位权限
        }
      })
      //#endif
      //#ifdef MP-WEIXIN
        this.getwxlocation()
      //#endif
    },
    //小程序再次授权定位
    getwxlocation(){
      let _this = this
      _this.wxgetlat=false
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        success: resData => {
          uni.request({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${resData.latitude},${resData.longitude}&key=LBOBZ-KSNKF-HIVJP-JXCC3-B3RRQ-ZUFKI`,
            success: async res => {
              let data = res.data.result.ad_info
              let obj = {
                city: data.city,
                district: data.district
              }
              _this.res.address = obj
              _this.successAdd = true
            }
          })
        },
        fail: () => {
           wx.getSetting({
              success: (res) => {
                  if (!res.authSetting['scope.userLocation']) {
                      wx.showModal({
                          content: '检测到您没打开定位权限，是否去设置打开？',
                          success: function (res) {
                              if (res.confirm) {
                                  wx.openSetting()
                                  _this.wxgetlat=true
                              }
                          },
                      });
                  }
              }
          })
        }
      })
    },
    //热门城市
    onHot(item) {
      let addArr = {
        city: item.name, //市
        province: this.province, //省
        district: '', //区
        lon: item.lon||0, //经度
        lat: item.lat||0,
        postalCode: Number(item.id), //id
      }
      uni.setStorageSync('addressList', addArr)
      this.$store.dispatch('changeAddress', addArr)
      this.cityId = item.id
      this.city = item.name
      /* this.$store.state.postalCode = item.id //id
      this.$store.state.city = item.name //id
      this.$store.state.lat = item.lat
      this.$store.state.lon = item.lon */
      this.lat = item.lat
      this.lon = item.lon
      // this.regionaldistrict()
      uni.navigateBack({
			  delta: 1,
      })
    },
    //区县展开
    chooseDown() {
      this.downShow = !this.downShow
    },
    async getHotCity() {
      try {
        const res = await this.$api.common.getHotCity()

        this.gotList = res.data
      } catch (e) {
        //TODO handle the exception
      }

    },
    //选择区县
    choose(item) {
      let addArr = {
        city: this.$store.state.city,
        province: this.province,
        district: item.name,
        lon: item.Lng||0, //经度
        lat: item.Lat||0,
        postalCode: Number(item.id), //id
      }
      uni.setStorageSync('addressList', addArr)
      this.$store.dispatch('changeAddress', addArr)
      this.district = item.name
      this.lat = item.Lat
      this.lon = item.Lng
      // const location = uni.getStorageSync('addressList')
      uni.navigateBack({
        delta: 1,
      })
    },
    //下拉关闭
    close(e) {
      this.isOpen = false
    },
    //下拉列表打开
    open(e) {
      this.isOpen = true
    },
    //搜索选择城市
    onCity(e) {
      this.city = e.name
      this.cityId = Number(e.id)
      let addArr = {
        city: e.name,
        province: this.province,
        district: '',
        lon: e.Lng||0, //经度
        lat: e.Lat||0,//纬度
        postalCode: Number(e.id), //id
      }
      this.$store.dispatch('changeAddress', addArr)
      this.isShow = false
      this.isListShow = true
      uni.setStorageSync('addressList', addArr)
      this.regionaldistrict()
      uni.navigateBack({
			  delta: 1,
      })
    },
    onBlur() {
      this.isShow = false
    },
    onChange(value) {
      this.isListShow = false
      this.search = value
      if (value.trim()) {
        this.isShow = true
        this.getSearch()
      } else {
        this.a = ''
        this.isShow = false
      }
    },
    getSearch() {
      //过滤城市
      if (this.search.length > 0) {
        this.a = this.arr.filter(v => {
          return JSON.stringify(v).indexOf(this.search.toUpperCase()) !== -1 //JSON.stringify()是必须的
        })
      }
    },

    //全部城市
    async regionaldistrict() {
      this.lodding = true
      try {
        const {
          data
        } = await this.$api.jsonData.regionalAll()

        let that = this
        data.Item.childlist.map(item1 => {
          item1.childlist.map(item2 => {
            if (item2.name === this.$store.state.city) {

              this.findDistrict = item2.childlist
            }
          })
        })
        this.lodding = false
      } catch (e) {
        this.lodding = false
      }
    },

    //获取市区
    async getCityList() {
      try {
        const {
          data
        } = await this.$api.jsonData.regionalCityGroupNew()
        this.cityList = data.list
        this.newArr = data.list
        const newArr = this.newArr
        this.pageLoading = true
        for (let i = 0; i < newArr.length; i++) {
          let data = newArr[i].data
          for (let j = 0; j < data.length; j++) {
            // 开始替换
            let name = data[j]
            // name.push(this.arr)
            this.arr.push(name)

          }
        }
      } catch (e) {

      }
    },

    //选择市
    addrestype(e) {
      let addArr = {
        city: e.name,
        province: this.province,
        district: '',
        lon: e.Lng||0, //经度
        lat: e.Lat||0,
        postalCode: Number(e.id), //id
      }
      this.city = e.name
      this.cityId = Number(e.id)
      this.$store.dispatch('changeAddress', addArr)
      uni.setStorageSync('addressList', addArr)
      uni.navigateBack({
        delta: 1,
      })
    }
  }
}
